package com.wenjie.original.service.impl;


import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.mybatisflex.core.query.QueryWrapper;
import com.wenjie.original.entity.SysAdmin;
import com.wenjie.original.entity.SysAdminRole;
import com.wenjie.original.entity.table.SysAdminRoleTableDef;
import com.wenjie.original.entity.vo.SysAdmin.SysAdminUpOrAddVo;
import com.wenjie.original.flex_config.baseInterface.Cus_ServiceImp;
import com.wenjie.original.mapper.SysUserMapper;
import com.wenjie.original.service.ISysAdminRoleService;
import com.wenjie.original.service.ISysAdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;


/**
 * 用户 业务层处理
 *
 * @author wenjie
 */
@Slf4j
@Service
public class SysAdminServiceImpl extends Cus_ServiceImp<SysUserMapper, SysAdmin> implements ISysAdminService {

    @Value("${password.salt}")
    private String salt;

    @Autowired
    private ISysAdminRoleService sysAdminRoleService;

    @Override
    @Transactional
    public void cusSave(SysAdminUpOrAddVo.AddVo addVo) {
        addVo.setSysAdminId(IdUtil.getSnowflakeNextId());

        if (addVo.getSysRoleIds() != null && addVo.getSysRoleIds().size() != 0) {
            List<SysAdminRole> sysRoles = new ArrayList<>();
            for (Long sysRoleId : addVo.getSysRoleIds()) {
                SysAdminRole sysAdminRole = new SysAdminRole();
                sysAdminRole.setSysAdminId(addVo.getSysAdminId());
                sysAdminRole.setSysRoleId(sysRoleId);
                sysRoles.add(sysAdminRole);
            }
            sysAdminRoleService.saveBatch(sysRoles);
        }

        // 对密码再次进行加盐
        addVo.setPassword(DigestUtil.md5Hex(addVo.getPassword() + salt));

        this.save(addVo);
    }

    @Override
    @Transactional
    public void cusUpdateById(SysAdminUpOrAddVo.UpVo upVo) {

        if (upVo.getSysRoleIds() != null && upVo.getSysRoleIds().size() != 0) {
            // 删除数据
            sysAdminRoleService.remove(QueryWrapper.create().where(SysAdminRoleTableDef.SYS_ADMIN_ROLE.SYS_ADMIN_ID.eq(upVo.getSysAdminId())));

            // 重新添加数据
            List<SysAdminRole> sysRoles = new ArrayList<>();
            for (Long sysRoleId : upVo.getSysRoleIds()) {
                SysAdminRole sysAdminRole = new SysAdminRole();
                sysAdminRole.setSysAdminId(upVo.getSysAdminId());
                sysAdminRole.setSysRoleId(sysRoleId);
                sysRoles.add(sysAdminRole);
            }
            sysAdminRoleService.saveBatch(sysRoles);
        }
        this.updateById(upVo);
    }
}
